"""
工具栏组件
"""

import tkinter as tk
from tkinter import messagebox, ttk
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ..main_window import MainWindow


class ToolbarMixin:
    """工具栏 Mixin 类"""
    
    def _create_toolbar(self: 'MainWindow'):
        """创建工具栏"""
        toolbar = ttk.Frame(self.root, padding=10)
        toolbar.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
        
        # 第一行按钮
        ttk.Button(
            toolbar, text="加载图片", command=self.load_image,
            bootstyle="success", width=12
        ).pack(side=tk.LEFT, padx=3)
        
        ttk.Button(
            toolbar, text="加载模型", command=self.load_model,
            bootstyle="primary", width=12
        ).pack(side=tk.LEFT, padx=3)
        
        ttk.Button(
            toolbar, text="自动分割", command=self.segment_auto,
            bootstyle="warning", width=12
        ).pack(side=tk.LEFT, padx=3)
        
        # 添加撤销/重做按钮
        self.undo_btn = ttk.Button(
            toolbar, text="↶ 撤销", command=self.undo,
            bootstyle="secondary-outline", width=10,
            state=tk.DISABLED
        )
        self.undo_btn.pack(side=tk.LEFT, padx=3)
        
        self.redo_btn = ttk.Button(
            toolbar, text="↷ 重做", command=self.redo,
            bootstyle="secondary-outline", width=10,
            state=tk.DISABLED
        )
        self.redo_btn.pack(side=tk.LEFT, padx=3)
        
        ttk.Button(
            toolbar, text="清除选择", command=self.clear_selection,
            bootstyle="secondary", width=12
        ).pack(side=tk.LEFT, padx=3)
        
        ttk.Button(
            toolbar, text="导出选中", command=self.export_selected,
            bootstyle="info", width=12
        ).pack(side=tk.LEFT, padx=3)
        
        ttk.Button(
            toolbar, text="添加到裁剪库", command=self.add_to_clip_library,
            bootstyle="info-outline", width=14
        ).pack(side=tk.LEFT, padx=3)
        
        ttk.Button(
            toolbar, text="打开裁剪库", command=self.open_clip_library,
            bootstyle="primary-outline", width=12
        ).pack(side=tk.LEFT, padx=3)
        
        ttk.Button(
            toolbar, text="RGB通道编辑", command=self.open_channel_editor,
            bootstyle="info-outline", width=13
        ).pack(side=tk.LEFT, padx=3)
        
        ttk.Button(
            toolbar, text="下载模型", command=self.download_model,
            bootstyle="secondary-outline", width=12
        ).pack(side=tk.LEFT, padx=3)
        
        # 第二行：选择模式和参数
        toolbar2 = ttk.Frame(self.root, padding=10)
        toolbar2.pack(side=tk.TOP, fill=tk.X, padx=5, pady=(0, 5))
        
        # 选择模式
        ttk.Label(toolbar2, text="选择模式:", font=("Arial", 10, "bold")).pack(side=tk.LEFT, padx=(5, 10))
        self.mode_var = tk.StringVar(value="auto")
        
        ttk.Radiobutton(
            toolbar2, text="自动", variable=self.mode_var, value="auto",
            command=self.change_mode, bootstyle="toolbutton"
        ).pack(side=tk.LEFT, padx=2)
        
        ttk.Radiobutton(
            toolbar2, text="单点", variable=self.mode_var, value="point",
            command=self.change_mode, bootstyle="toolbutton"
        ).pack(side=tk.LEFT, padx=2)
        
        ttk.Radiobutton(
            toolbar2, text="框选", variable=self.mode_var, value="box",
            command=self.change_mode, bootstyle="toolbutton"
        ).pack(side=tk.LEFT, padx=2)
        
        # 景深模型选择
        ttk.Label(toolbar2, text="景深模型:", font=("Arial", 9)).pack(side=tk.LEFT, padx=(15, 5))
        default_depth_model = self.config.get('depth_mode.default_model', 'DPT_Large')
        self.depth_model_var = tk.StringVar(value=default_depth_model)
        depth_model_combo = ttk.Combobox(
            toolbar2,
            textvariable=self.depth_model_var,
            values=['DPT_Large', 'DPT_Hybrid', 'MiDaS_small'],
            width=12,
            state="readonly"
        )
        depth_model_combo.pack(side=tk.LEFT, padx=2)
        
        # 模型说明标签
        model_desc = {
            'DPT_Large': '(1.4GB, 最准确)',
            'DPT_Hybrid': '(700MB, 中等)',
            'MiDaS_small': '(100MB, 最快)'
        }
        self.depth_model_desc_label = ttk.Label(
            toolbar2, 
            text=model_desc.get(default_depth_model, '(1.4GB, 最准确)'),
            font=("Arial", 8),
            foreground="gray"
        )
        self.depth_model_desc_label.pack(side=tk.LEFT, padx=(2, 5))
        
        # 绑定模型选择变化事件
        def on_depth_model_change(*args):
            model = self.depth_model_var.get()
            # 如果切换了模型且之前已加载，需要重新加载
            if self.depth_model_type != model and self.depth_estimator.is_loaded():
                if messagebox.askyesno(
                    "切换景深模型",
                    f"检测到景深模型已切换：\n\n"
                    f"当前：{self.depth_model_type}\n"
                    f"新模型：{model}\n\n"
                    f"是否重新加载？（下次生成景深图时生效）",
                    parent=self.root
                ):
                    # 清除当前模型（下次使用时会自动加载新模型）
                    self.depth_estimator.model = None
                    self.logger.info(f"已清除旧模型，将在下次使用时加载 {model}")
            
            self.depth_model_type = model
            self.depth_model_desc_label.config(text=model_desc.get(model, ''))
            self.logger.info(f"景深模型设置为: {model}")
        
        self.depth_model_var.trace('w', on_depth_model_change)
        
        # 景深图开关（控制显示和SAM输入）
        self.use_depth_var = tk.BooleanVar(value=False)
        depth_switch = ttk.Checkbutton(
            toolbar2,
            text="使用景深图",
            variable=self.use_depth_var,
            command=self._on_depth_mode_toggle,
            bootstyle="info-round-toggle"
        )
        depth_switch.pack(side=tk.LEFT, padx=(20, 5))
        
        ttk.Label(
            toolbar2,
            text="(显示景深图+给SAM提供深度信息)",
            font=("Arial", 8),
            foreground="gray"
        ).pack(side=tk.LEFT, padx=(0, 5))
        
        # rembg背景移除开关
        self.use_rembg_var = tk.BooleanVar(value=False)
        rembg_switch = ttk.Checkbutton(
            toolbar2,
            text="Rembg去背景",
            variable=self.use_rembg_var,
            command=self._on_rembg_toggle,
            bootstyle="warning-round-toggle"
        )
        rembg_switch.pack(side=tk.LEFT, padx=(20, 5))
        
        ttk.Label(
            toolbar2,
            text="(AI自动去除背景)",
            font=("Arial", 8),
            foreground="gray"
        ).pack(side=tk.LEFT, padx=(0, 5))
        
        # 模型类型选择
        ttk.Label(toolbar2, text="模型:", font=("Arial", 10, "bold")).pack(side=tk.LEFT, padx=(20, 5))
        self.model_type_var = tk.StringVar(
            value=self.config.get('model.default_type', 'vit_b')
        )
        model_combo = ttk.Combobox(
            toolbar2, textvariable=self.model_type_var,
            values=self.config.get('model.available_models', ['vit_h', 'vit_l', 'vit_b']),
            width=10, state="readonly"
        )
        model_combo.pack(side=tk.LEFT, padx=5)
        
        # 平滑开关
        self.smooth_mask_var = tk.BooleanVar(value=True)
        smooth_check = ttk.Checkbutton(
            toolbar2,
            text="边缘平滑",
            variable=self.smooth_mask_var,
            command=self._on_smooth_toggle,
            bootstyle="success-round-toggle"
        )
        smooth_check.pack(side=tk.LEFT, padx=(20, 5))
        
        # 平滑提示
        ttk.Label(
            toolbar2,
            text="(消除锯齿)",
            font=("Arial", 9),
            foreground="gray"
        ).pack(side=tk.LEFT, padx=(0, 5))
    
    def _create_statusbar(self: 'MainWindow'):
        """创建状态栏"""
        self.status_bar = ttk.Label(
            self.root, text="就绪", relief=tk.SUNKEN, anchor=tk.W, padding=5
        )
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 进度条
        self.progress = ttk.Progressbar(
            self.root, mode='indeterminate', length=300, bootstyle="success-striped"
        )
    
    def update_status(self: 'MainWindow', message: str):
        """更新状态栏"""
        self.status_bar.config(text=message)
        self.root.update_idletasks()
        self.logger.info(f"状态: {message}")

